<template>
  <view class="page">
    <view class="section">
      <button @click="getWeather">获取明天天气预报</button>
      <view class="weather-box">
        <view v-if="loading" class="loading">加载中...</view>
        <view v-else-if="errorMsg" class="error">错误：{{ errorMsg }}</view>
        <view v-else-if="weather" class="weather-info">
          <text>📅 日期：{{ weather.date }}</text>
          <text>📆 星期：{{ weather.week }}</text>
          <text>🌡 最高温：{{ weather.high }}</text>
          <text>❄ 最低温：{{ weather.low }}</text>
          <text>🌫 天气：{{ weather.type }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      weather: null,
      loading: false,
      errorMsg: "",
      weatherUrl: "http://t.weather.sojson.com/api/weather/city/101230501"
    };
  },
  methods: {
    getWeather() {
      this.loading = true;
      this.errorMsg = "";
      this.weather = null;

      // 获取明天的日期字符串（格式：YYYY-MM-DD）
      const tomorrow = new Date(Date.now() + 24 * 60 * 60 * 1000);
      const y = tomorrow.getFullYear();
      const m = String(tomorrow.getMonth() + 1).padStart(2, "0");
      const d = String(tomorrow.getDate()).padStart(2, "0");
      const tomorrowStr = `${y}-${m}-${d}`;

      console.log("目标日期（明天）:", tomorrowStr);

      uni.request({
        url: this.weatherUrl,
        method: "GET",
        success: (res) => {
          if (res.statusCode !== 200) {
            this.errorMsg = "接口响应错误：" + res.statusCode;
            return;
          }
          const data = res.data?.data;
          if (!data || !data.forecast) {
            this.errorMsg = "返回数据异常";
            return;
          }

          // 精确匹配明天日期
          let forecast = data.forecast.find((f) => f.ymd === tomorrowStr);
          if (!forecast) forecast = data.forecast[1]; // 兼容结构中"明天"常为第二项

          if (!forecast) {
            this.errorMsg = "未找到明日天气数据";
            return;
          }

          // 去掉"高温""低温"等前缀，只保留温度值
          const cleanTemp = (t) => (t ? t.replace(/[高低温\s]/g, "") : "");

          this.weather = {
            date: forecast.ymd,
            week: forecast.week,
            high: cleanTemp(forecast.high),
            low: cleanTemp(forecast.low),
            type: forecast.type,
          };
          console.log("明天天气：", this.weather);
        },
        fail: (err) => {
          console.error("天气请求失败：", err);
          this.errorMsg = "请求失败：" + err.errMsg;
        },
        complete: () => {
          this.loading = false;
        },
      });
    }
  }
};
</script>

<style>
.page {
  padding: 30rpx;
}
.section {
  margin-bottom: 40rpx;
}
.weather-box {
  margin-top: 20rpx;
  border: 1px solid #ccc;
  padding: 20rpx;
  border-radius: 10rpx;
}
.weather-info {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}
.weather-info text {
  display: block;
  font-size: 28rpx;
  color: #333;
}
.loading {
  text-align: center;
  color: #007AFF;
}
.error {
  color: red;
  text-align: center;
}
</style>